package org.iteam.xlz.manager.action.report;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.iteam.core.utils.DateUtil;
import org.iteam.web.struts.action.JsonServletAction;
import org.iteam.xlz.core.entity.report.AppReport;
import org.iteam.xlz.core.service.report.AppReportService;

@SuppressWarnings("unchecked")
@Results({@Result(name="INDEX",type="freemarker",location="/WEB-INF/content/report/app/index.html"),
	      @Result(name="DOWNLOAD",type="stream",params={"contentType","application/octet-stream",
	    		  "inputName","inputStream","contentDisposition","attachment;filename=${fileName}",
	    		  "bufferSize","4096"})})
public class AppReportAction extends JsonServletAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1242530539841927597L;

	private final String PATH="/report/app";
	@Action(PATH+"/index")
	public String index(){
		return "INDEX";
	}
	
	@Action(PATH+"/query")
	public String query() throws ParseException{
		Date first = null;
		Date last = null;
		if(StringUtils.isNotBlank(leftCreateTime)||StringUtils.isNotBlank(rightCreateTime)){
			first=DateUtil.parseDate(leftCreateTime);
			last=DateUtil.parseDate(rightCreateTime);
		}
		map.put("total",AppReportService.getInstance().counts(first,last));
		map.put("rows",AppReportService.getInstance().query(first,last,page,rows,true));
		return "MAP";
	}
	
	@Action(PATH+"/download")
	public String download() throws ParseException{
		setInputStream();
		return "DOWNLOAD";
	}
	
	public InputStream getInputStream() {
		return new ByteArrayInputStream(bytes);
	}
	
	private void setInputStream() throws ParseException{
		Date first = null;
		Date last = null;
		if(StringUtils.isNotBlank(leftCreateTime)||StringUtils.isNotBlank(rightCreateTime)){
			first=DateUtil.parseDate(leftCreateTime);
			last=DateUtil.parseDate(rightCreateTime);
		}
		List<AppReport> list=AppReportService.getInstance().query(first,last,page,rows,false);
		// 第一步，创建一个webbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
		// 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
		HSSFSheet sheet = wb.createSheet("app统计表");
		// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
		HSSFRow row = sheet.createRow((int) 0);
		// 第四步，创建单元格
		//订单编号oid,手机号码uid,商品库存名称,商品上架名称ppid,票券编号tid,充值编号rid,交易号tradeNo,交易类型ordertype,总金额totalprice,数量amount,支付方式paytype,订单状态status,支付时间paytime,第三方流水号thirdid,创建时间createtime
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("日期");
		cell = row.createCell(1);
		cell.setCellValue("Android新增用户");
		cell = row.createCell(2);
		cell.setCellValue("ios新增用户");
		cell = row.createCell(3);
		cell.setCellValue("日活跃用户");
		cell = row.createCell(4);
		cell.setCellValue("月活跃用户");
		cell = row.createCell(5);
		cell.setCellValue("Android累计用户");
		cell = row.createCell(6);
		cell.setCellValue("IOS累计用户");

		// 第五步，写入实体数据 实际应用中这些数据从数据库得到，
		for(int i=1;i<=list.size();i++){
			row = sheet.createRow(i);
			row.createCell(0).setCellValue(list.get(i-1).getTime());
			row.createCell(1).setCellValue(list.get(i-1).getAndroidNew());
			row.createCell(2).setCellValue(list.get(i-1).getIosNew());
			row.createCell(3).setCellValue(list.get(i-1).getDayUser());
			row.createCell(4).setCellValue(list.get(i-1).getMonthUser());
			row.createCell(5).setCellValue(list.get(i-1).getAndroidTotal());
			row.createCell(6).setCellValue(list.get(i-1).getIosTotal());
		}
		// 第六步，将文件存到指定位置
		try
		{
			ByteArrayOutputStream  os=new ByteArrayOutputStream();
			wb.write(os);
			bytes=os.toByteArray();
			fileName = DateUtil.formatDate(new Date()) + new Random().nextInt(999)+".xls";//这里是给excel文件设置文件名（时间+一个随机数）
			wb.close();
		}catch (Exception e){
			e.printStackTrace();
		}
	}
	
	private String leftCreateTime;
	private String rightCreateTime;
	private byte[] bytes;
	private String fileName;
	
	int page,rows;
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public void setLeftCreateTime(String leftCreateTime) {
		this.leftCreateTime = leftCreateTime;
	}

	public void setRightCreateTime(String rightCreateTime) {
		this.rightCreateTime = rightCreateTime;
	}

	public String getFileName() {
		return fileName;
	}
}
